<?php
	class GerarExcel{
		
		private $Consulta;	
		private $NumeroColunas;
		private $Error;
		
		public function SetConsulta($_value)
		{
			$this->Consulta = $_value;
		}
		 
		public function GetConsulta()
		{
			return $this->Consulta;
		}
		
		public function GetError()
		{
			return $this->Error;
		}
		
		
		
		public function Gerar()
		{
			$this->Cabecalho();
		}			

		
		private function Cabecalho()
		{	
			$_query = mysql_query($this->Consulta);			
			if($_query)
			{
				$this->ForcarDownload(); 
			
				$this->NumeroColunas = mysql_num_fields($_query);
				
				$i = 0;
				echo "
					<table cellpadding='3' cellspacing='3' border='1'>
						<thead>
							<tr>";
								while($i < $this->NumeroColunas)
								{
									echo "<th>".mysql_field_name($_query, $i)."</th>";
									$i++;
								}						
					echo	"</tr>
						</thead>
						<tbody>";						
							$this->Dados($_query);							
				echo "	</tbody>
					</table>";
			}
			else 
				return	$this->Error = "<strong>Falha com consulta SQL:</strong> ".mysql_error();  
			
		}
		
		
		private function Dados($_query)
		{				
			while($linha = mysql_fetch_array($_query))
			{
				$i = 0;
				echo "<tr>";
						while($i < $this->NumeroColunas)
						{
							echo "<td>".$linha[mysql_field_name($_query, $i)]."</td>";
							$i++;
						}	
				echo"</tr>";				
			}
		}
		
		public function ForcarDownload()
		{
			header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
			header ("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
			header ("Cache-Control: no-cache, must-revalidate");
			header ("Pragma: no-cache");
			header ("Content-type: application/x-msexcel");
			//header("Content-type: application/vnd.ms-excel"); 
			header("Content-type: application/force-download"); 
			header ("Content-Disposition: attachment; filename=Relatorio.xls" );			
		}

	}
?>